package com.zx.练习题._2022面试题收集;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import lombok.extern.slf4j.Slf4j;

/**
 * 线程切换的具体实现
 * 2个线程，
 */
@Slf4j
public class Demo1 {


    public static void main(String[] args) {
        AtomicInteger num = new AtomicInteger(0);
        AtomicBoolean bool = new AtomicBoolean(true);
        // 1,3,5,7
        new Thread(() -> {
            while (true && num.get() < 10) {
                if (bool.get() && num.get() < 10) {
                    log.info("{}", num.incrementAndGet());
                    bool.compareAndSet(true, false);
                }
                sleep(1000L);
            }
        }, "thread-a").start();
        // 2,4,6,8
        new Thread(() -> {
            while (true && num.get() < 10) {
                if (!bool.get() && num.get() < 10) {
                    log.info("{}", num.incrementAndGet());
                    bool.compareAndSet(false, true);
                }
                sleep(1000L);
            }
        }, "thread-b").start();
    }

    public static void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
